// ============================== 导入依赖 ============================== //

import Vue from 'vue'

// ============================== 导出工具 ============================== //

export default {
  /**
   * 转换设备树
   *
   * @param {Array} tree 结构树
   * @param {String} deviceCategoryId 设备类型 ID
   * @param {Array} list 当前区域的设备列表
   */
  transDeviceTree(tree, deviceCategoryId, list) {
    if (!deviceCategoryId) return tree

    const nameKey = getNameKey(deviceCategoryId)
    tree.forEach((node) => {
      const deviceList = node[`device_${deviceCategoryId}`]
      const showList = (deviceList || []).map((device) => ({
        id: device.id,
        name: device[nameKey],
        device,
        disabled: list.some((item) => item.deviceId === device.id),
      }))
      // 未加载过设备的占位空结点
      const emptyList = node.children.length || deviceList ? [] : [{ id: `${node.id}-empty` }]
      // 响应式设置
      Vue.set(node, 'nodes', [...showList, ...node.children, ...emptyList])
      this.transDeviceTree(node.children, deviceCategoryId, list)
    })
    return tree
  },
}

// ============================== 内部方法 ============================== //

const getNameKey = (deviceCategoryId) => {
  if (deviceCategoryId === '2') return 'name'
  if (deviceCategoryId === '3') return 'entranceName'
  if (deviceCategoryId === '4') return 'defenceName'
  return 'deviceName'
}
